<title="学生管理页面">
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生管理</title>
    <style>
        body { font-family: Arial, sans-serif; padding: 20px; max-width: 1200px; margin: auto; background-color: #f4f4f9; }
        h1, h2, h3 { color: #333; }
        input[type="text"], input[type="file"] { width: calc(100% - 22px); padding: 8px; margin-bottom: 10px; box-sizing: border-box; border: 1px solid #ccc; border-radius: 4px; }
        button { padding: 8px 16px; background-color: #007bff; color: white; border: none; cursor: pointer; border-radius: 4px; transition: background-color 0.3s; margin-right: 10px; }
        button:hover { background-color: #0056b3; }
        table { width: 100%; border-collapse: collapse; margin-bottom: 20px; background-color: #fff; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); }
        th, td { padding: 12px; text-align: left; border-bottom: 1px solid #ddd; position: relative; }
        th { background-color: #f4f4f4; cursor: pointer; user-select: none; }
        th::after {
            content: '';
            float: right;
            margin-left: 5px;
            border: 5px solid transparent;
            border-bottom-color: #444;
        }
        th.asc::after {
            border-bottom: none;
            border-top: 5px solid #444;
        }
        th.desc::after {
            border-top: none;
            border-bottom: 5px solid #444;
        }
        .card { border: 1px solid #ccc; border-radius: 5px; padding: 10px; width: 250px; display: inline-block; margin: 10px; vertical-align: top; background-color: #fff; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); }
        .page-break { page-break-after: always; }
        nav a { margin-right: 10px; color: #007bff; text-decoration: none; }
        nav a:hover { text-decoration: underline; }
        .error-message { color: red; margin-top: 10px; }
        .modal { display: none; position: fixed; z-index: 1; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.4); }
        .modal-content { background-color: #fefefe; margin: 15% auto; padding: 20px; border: 1px solid #888; width: 80%; max-width: 500px; border-radius: 8px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); }
        .close { color: #aaa; float: right; font-size: 28px; font-weight: bold; cursor: pointer; }
        .close:hover, .close:focus { color: black; text-decoration: none; cursor: pointer; }
    </style>
</head>
<body>
    <nav>
        <a href="/">首页</a>
        <a href="/students">学生管理</a>
        <a href="/exams">考试管理</a>
        <a href="/scores">成绩管理</a>
        <a href="/analysis">成绩分析</a>
    </nav>

    <h1>学生管理</h1>
    <form id="addStudentForm">
        <input type="text" id="studentName" placeholder="姓名" required>
        <input type="text" id="studentIdCard" placeholder="身份证号" required>
        <button type="submit">添加学生</button>
        <button onclick="triggerFileUpload()">批量导入学生</button>
        <input type="file" id="studentsFile" accept=".xlsx,.xls" style="display:none;" onchange="handleFileUpload()">
    </form>
    <div id="errorMessage" class="error-message"></div>

    <table id="studentsTable">
        <thead>
            <tr>
                <th onclick="sortTable(0)">ID</th>
                <th onclick="sortTable(1)">姓名</th>
                <th onclick="sortTable(2)">性别</th>
                <th onclick="sortTable(3)">出生日期</th>
                <th onclick="sortTable(4)">年龄</th>
                <th onclick="sortTable(5)">籍贯</th>
                <th onclick="sortTable(6)">星座</th>
                <th onclick="sortTable(7)">生肖</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            {% for student in students %}
            <tr data-id="{{ student.id }}">
                <td>{{ student.id }}</td>
                <td>{{ student.name }}</td>
                <td>{{ student.gender }}</td>
                <td>{{ student.birthDate }}</td>
                <td>{{ student.age }}</td>
                <td>{{ student.region }}</td>
                <td>{{ student.zodiacSign }}</td>
                <td>{{ student.chineseZodiac }}</td>
                <td>
                    <button onclick="editStudent({{ student.id }})">编辑</button>
                    <button onclick="deleteStudent({{ student.id }})">删除</button>
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>

    <!-- 编辑学生模态框 -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeModal()">&times;</span>
            <h2>编辑学生信息</h2>
            <form id="editStudentForm">
                <input type="hidden" id="editStudentId">
                <input type="text" id="editStudentName" placeholder="姓名" required>
                <input type="text" id="editStudentIdCard" placeholder="身份证号" required>
                <button type="submit">保存更改</button>
            </form>
        </div>
    </div>

    <script>
        document.getElementById('addStudentForm').addEventListener('submit', function(event) {
            event.preventDefault();
            const name = document.getElementById('studentName').value;
            const idCard = document.getElementById('studentIdCard').value;

            fetch('/add_student', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `name=${encodeURIComponent(name)}&idCard=${encodeURIComponent(idCard)}`
            })
            .then(response => response.json())
            .then(students => {
                updateStudentsTable(students);
                document.getElementById('addStudentForm').reset();
            });
        });

        function triggerFileUpload() {
            document.getElementById('studentsFile').click();
        }

        function handleFileUpload() {
            const fileInput = document.getElementById('studentsFile');
            const file = fileInput.files[0];

            if (!file) {
                showError("请选择一个文件");
                return;
            }

            const formData = new FormData();
            formData.append('file', file);

            fetch('/upload_students', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (response.status !== 200) {
                    return response.json().then(data => {
                        throw new Error(data.error || "文件上传失败");
                    });
                }
                return response.json();
            })
            .then(students => {
                updateStudentsTable(students);
                hideError();
            })
            .catch(error => {
                showError(error.message);
            });
        }

        function deleteStudent(studentId) {
            fetch(`/delete_student/${studentId}`, {
                method: 'DELETE'
            })
            .then(response => response.json())
            .then(students => {
                updateStudentsTable(students);
            });
        }

        function editStudent(studentId) {
            const modal = document.getElementById('editModal');
            modal.style.display = 'block';
            const student = system.students.find(s => s.id === studentId);
            document.getElementById('editStudentId').value = student.id;
            document.getElementById('editStudentName').value = student.name;
            document.getElementById('editStudentIdCard').value = student.idCard;
        }

        document.getElementById('editStudentForm').addEventListener('submit', function(event) {
            event.preventDefault();
            const studentId = parseInt(document.getElementById('editStudentId').value);
            const name = document.getElementById('editStudentName').value;
            const idCard = document.getElementById('editStudentIdCard').value;

            fetch('/update_student', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `id=${encodeURIComponent(studentId)}&name=${encodeURIComponent(name)}&idCard=${encodeURIComponent(idCard)}`
            })
            .then(response => response.json())
            .then(students => {
                updateStudentsTable(students);
                closeModal();
            });
        });

        function closeModal() {
            document.getElementById('editModal').style.display = 'none';
        }

        function updateStudentsTable(students) {
            const tbody = document.querySelector('#studentsTable tbody');
            tbody.innerHTML = '';
            students.forEach(student => {
                const row = `
                    <tr data-id="${student.id}">
                        <td>${student.id}</td>
                        <td>${student.name}</td>
                        <td>${student.gender}</td>
                        <td>${student.birthDate}</td>
                        <td>${student.age}</td>
                        <td>${student.region}</td>
                        <td>${student.zodiacSign}</td>
                        <td>${student.chineseZodiac}</td>
                        <td>
                            <button onclick="editStudent(${student.id})">编辑</button>
                            <button onclick="deleteStudent(${student.id})">删除</button>
                        </td>
                    </tr>`;
                tbody.insertAdjacentHTML('beforeend', row);
            });
        }

        function showError(message) {
            document.getElementById('errorMessage').textContent = message;
        }

        function hideError() {
            document.getElementById('errorMessage').textContent = '';
        }

        // 初始化系统对象
        const system = {
            students: {{ students | tojson }},
            exams: []
        };

        // 表格排序函数
        let sortDirection = {};
        function sortTable(columnIndex) {
            const table = document.getElementById('studentsTable');
            const rows = Array.from(table.rows).slice(1); // 跳过表头行

            // 获取当前列的排序方向
            const currentDir = sortDirection[columnIndex] || 'asc';

            // 根据数据类型选择比较函数
            const compareFunction = columnIndex === 3 ? dateCompare : defaultCompare;

            // 排序行
            rows.sort((rowA, rowB) => {
                const cellA = rowA.cells[columnIndex].innerText.trim();
                const cellB = rowB.cells[columnIndex].innerText.trim();

                const comparison = compareFunction(cellA, cellB);
                return currentDir === 'asc' ? comparison : -comparison;
            });

            // 将排序后的行重新插入表格
            rows.forEach(row => table.tBodies[0].appendChild(row));

            // 更新排序方向
            sortDirection[columnIndex] = currentDir === 'asc' ? 'desc' : 'asc';

            // 更新表头箭头
            const headers = table.querySelectorAll('th');
            headers.forEach(header => header.classList.remove('asc', 'desc'));
            headers[columnIndex].classList.add(sortDirection[columnIndex]);
        }

        function defaultCompare(a, b) {
            return a.localeCompare(b);
        }

        function dateCompare(dateA, dateB) {
            const [monthA, dayA] = dateA.split('-').map(Number);
            const [monthB, dayB] = dateB.split('-').map(Number);
            if (monthA === monthB) {
                return dayA - dayB;
            }
            return monthA - monthB;
        }
    </script>
</body>
</html>